import { Watcher } from './Watcher'

export class Compiler {
	constructor(vm) {
		this.vm = vm
		this.el = vm.$el

		this.compile(this.el)
	}

	compile(el) {
		let childNodes = [...el.childNodes]
		childNodes.forEach((node) => {
			if (this.isTextNode(node)) {
				this.compileText(node)
			} else if (this.isElementNode(node)) {
				this.compileElement(node)
			}

			if (node.childNodes && node.childNodes.length) {
				this.compile(node)
			}
		})
	}
	compileText(node) {
		let val = node.textContent
		let reg = /\{\{(.+?)\}\}/

		if (reg.test(val)) {
			let key = RegExp.$1.trim()
			node.textContent = val.replace(reg, this.vm[key])

			new Watcher(this.vm, key, (newValue) => {
				node.textContent = newValue
			})
		}
	}

	compileElement(node) {
		let self = this,
			props = node.getAttributeNames(),
			reg = /^c-(\w+)/,
			reg2 = /\((.+)\)/,
			reg3 = /\'(.+)\'/,
			reg4 = /^\d+$/,
			reg5 = /(\w+)\(/,
			value,
			methodName
		props.forEach((key) => {
			if (reg.test(key)) {
				methodName = RegExp.$1.trim()
			}

			let qian = node.getAttribute(key)

			if (reg2.test(qian)) {
				value = RegExp.$1.trim()
				if (reg4.test(value)) {
					value = parseInt(value)
				}
				if (reg3.test(value)) {
					value = RegExp.$1.trim
				}
			}

			if (reg5.test(qian)) {
				qian = RegExp.$1.trim
			}
			console.log(qian)
			console.log(methodName)
			console.log(value)
			node.addEventListener(methodName, function (e) {
				self.vm[qian](value ? (self.vm[value] ? self.vm[value] : value) : e)
			})
		})
	}

	isTextNode(node) {
		return node.nodeType === 3
	}

	isElementNode(node) {
		return node.nodeType === 1
	}
}
